<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>通讯录</title>

		<script type="text/javascript">
			//保存联系人
			function save() {
				localStorage.setItem(mobilephone.value, username.value);
				//每次添加联系人都要刷新表格
				getAllList();
			}
			//根据号码查找联系人姓名
			function search() {
				result.innerHTML = search_phone.value + " 机主是:" +
					localStorage.getItem(search_phone.value);
			}

			function getAllList() {
				//获取到表格的div节点
				var element = document.getElementById("list");
				//判断storage有没有数据
				if(localStorage.length > 0) {
					
					//拼接表头
					element = "<table border = '1'>";
					element += "<tr><th>姓名</th><th>号码</th></tr>";
					
					//拼接每条数据td
					for(var i = 0; i < localStorage.length; i++) {
						var key = localStorage.key(i);
						var name = localStorage.getItem(key);
						element += "<tr><td>" + name + "</td><td>" + key + "</td></tr>"
					}
					
					//拼接表尾
					element += "</table>";
					
					//把拼接好了的html代码插入到list div中
					list.innerHTML = element;
				} else {
					list.innerHTML = "没有数据!!!"
				}
			}
		</script>

	</head>
	<!--每次界面加载就显示-->
	<body onload="getAllList()">
		<div style="border: 2px dashed #ccc;width: 320px; text-align: center;">
			<label for="username">姓名:</label>
			<input type="text" name="username" id="username" value="" />
			<br />
			<label for="mobilephone">手机:</label>
			<input type="number" name="mobilephone" id="mobilephone" value="" />
			<br />
			<!--<label for="company">公司:</label>
			<input type="text" name="company" id="company" value="" />
			<br />-->
			<input type="button" name="" id="" value="添加记录" onclick="save()" />

			<hr />
			<label for="search_phone">输入手机号码:</label>
			<input type="number" name="search_phone" id="search_phone" value="" />
			<input type="button" value="查找机主" onclick="search()" />
			<p id="result">
				<br />
			</p>

		</div>
		<br />
		<div id="list">
			<tr><th>姓名</th><th>号码</th></tr>
			
			
		</div>
	</body>

</html>